﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MyGeneration.dOOdads;
using System.Data;
using POSSystem.BLL;

namespace WebUI.Controls
{
    public delegate void NeedDataSource(object sender, EventArgs e);

    public partial class BaseListControl : BaseControl
    {
        public const String SORT_ASC = "asc";
        public const String SORT_DESC = "desc";
        public const String DEFAULT_FILTER = "";

        protected void Page_Load(object sender, EventArgs e)
        {
            base.Page_Load(sender, e);
        }

        public String SourceObjectSessionID
        {
            get 
            { 
                if(ViewState[ClientID + "_SourceObjectSessionID"] == null)
                    ViewState[ClientID + "_SourceObjectSessionID"] = Utilities.CreateMD5Hash(ClientID + "_SourceObjectSessionID");//Guid.NewGuid().ToString() + "_" + ClientID + "_griddatasource";
                return ViewState[ClientID + "_SourceObjectSessionID"].ToString();
            }
            set { ViewState[ClientID + "_SourceObjectSessionID"] = value; }
        }

        public String OnDblClick
        {
            get
            {
                if (ViewState[ClientID + "_OnDblClick"] == null)
                    ViewState[ClientID + "_OnDblClick"] = "";
                return ViewState[ClientID + "_OnDblClick"].ToString();
            }
            set { ViewState[ClientID + "_OnDblClick"] = value; }
        }

        public String OnClientClick
        {
            get
            {
                if (ViewState[ClientID + "_OnClientClick"] == null)
                    ViewState[ClientID + "_OnClientClick"] = "";
                return ViewState[ClientID + "_OnClientClick"].ToString();
            }
            set { ViewState[ClientID + "_OnClientClick"] = value; }
        }

        public Unit Width
        {
            get { return grid.Width; }
            set { grid.Width = value; }
        }

        public Unit Height
        {
            get { return grid.Height; }
            set { grid.Height = value; }
        }

        public GridLines GridLineStyle
        {
            get { return grid.GridLines; }
            set { grid.GridLines = value; }
        }

        public BorderStyle GridBorder
        {
            get { return grid.BorderStyle; }
            set { grid.BorderStyle = value; }
        }

        public Unit GridBorderWidth
        {
            get { return grid.BorderWidth; }
            set { grid.BorderWidth = value; }
        }

        public System.Drawing.Color GridBorderColor
        {
            get { return grid.BorderColor; }
            set { grid.BorderColor = value; }
        }

        public string  CssClass
        {
            get { return grid.CssClass; }
            set { grid.CssClass = value; }
        }

        public DataGridColumnCollection Columns
        {
            get { return grid.Columns; }
        }

        public String SortExpression
        {
            get
            {
                if (ViewState[ClientID + "_SortExpression"] == null)
                    ViewState[ClientID + "_SortExpression"] = "";
                return ViewState[ClientID + "_SortExpression"].ToString();
            }
            set
            {
                ViewState[ClientID + "_SortExpression"] = value;
            }
        }

        public String SortDirection
        {
            get
            {
                if (ViewState[ClientID + "_SortDirection"] == null)
                    ViewState[ClientID + "_SortDirection"] = "";
                return ViewState[ClientID + "_SortDirection"].ToString();
            }
            set
            {
                ViewState[ClientID + "_SortDirection"] = value;
            }
        }

        Boolean saveOnCommit;

        public Boolean SaveOnCommit
        {
            get { return saveOnCommit; }
            set { saveOnCommit = value; }
        }

        Boolean allowSelecting;
        public Boolean AllowSelecting
        {
            get
            {
                return allowSelecting;
            }
            set
            {
                allowSelecting = value; 
                if(grid.Columns.Count > 0 && grid.Columns[0].HeaderText == "")
                    grid.Columns[0].Visible = value;
            }
        }

        public Boolean ShowHeader
        {
            get { return grid.ShowHeader; }
            set { grid.ShowHeader = value;}
        }

        public TableItemStyle AlternatingItemStyle
        {
            get { return grid.AlternatingItemStyle; }
        }

        public int SelectedIndex
        {
            get
            {
                return grid.SelectedIndex;
            }
            set
            {
                grid.SelectedIndex = value;
            }
        }

        public SqlClientEntity SourceObject
        {
            get
            {
                return Session[SourceObjectSessionID] == null ? null : (SqlClientEntity)Session[SourceObjectSessionID];
            }
            set
            {
                Session.Remove(SourceObjectSessionID); Session[SourceObjectSessionID] = value;
            }
        }

        public String Filter
        {
            get
            {
                if (SourceObject != null)
                    return SourceObject.Filter;
                return "";
            }
            set
            {
                if (SourceObject != null)
                    SourceObject.Filter = value;
            }
        }

        public String Sort
        {
            get
            {
                if(SourceObject != null)
                    return SourceObject.Sort;
                return "";
            }
            set
            {
                if (SourceObject != null)
                    SourceObject.Sort = value;
            }
        }

        public Boolean AllowPaging
        {
            get
            {
                return grid.AllowPaging && grid.AllowCustomPaging;
            }
            set
            {
                grid.AllowPaging = value;
                grid.AllowCustomPaging = value;
            }
        }

        public Boolean AllowSorting
        {
            get
            {
                return grid.AllowSorting;
            }
            set
            {
                grid.AllowSorting = value;
            }
        }

        public Boolean ShowFooter
        {
            get
            {
                return grid.ShowFooter;
            }
            set
            {
                grid.ShowFooter = value;
            }
        }

        public int PageSize
        {
            get
            {
                return grid.PageSize;
            }
            set
            {
                grid.PageSize = value;
            }
        }

        public int CurrentPageIndex
        {
            get { return grid.CurrentPageIndex; }
            set { grid.CurrentPageIndex = value; }
        }

        public NeedDataSource OnNeedDataSource
        {
            get;
            set;
        }

        public virtual void Refresh()
        {
            Sort = (SortExpression + " " + SortDirection).Trim();
            if (AllowPaging)
            {
                if (OnNeedDataSource != null)
                {
                    EventArgs e = new EventArgs();
                    OnNeedDataSource(this, e);
                }
                else
                {
                    grid.VirtualItemCount = SourceObject.RowCount;

                    int pageRowNum = PageSize;
                    if ((CurrentPageIndex + 1) * PageSize > SourceObject.RowCount)
                        pageRowNum = grid.VirtualItemCount % PageSize;
                    int fromIndex = PageSize * CurrentPageIndex;

                    DataTable table = SourceObject.DefaultView.Table.Clone();
                    for (int i = 0; i < pageRowNum && i + fromIndex < SourceObject.RowCount; i++)
                    {
                        table.ImportRow(SourceObject.DefaultView[i + fromIndex].Row);
                    }

                    grid.DataSource = table;
                }
                grid.DataBind();
            }
            else
            {
                if (OnNeedDataSource != null)
                {
                    EventArgs e = new EventArgs();
                    OnNeedDataSource(this, e);
                }
                else
                    grid.DataSource = SourceObject.DefaultView;

            }

            grid.DataBind();
            ScriptManager.RegisterClientScriptBlock(this, typeof(Page), Guid.NewGuid().ToString(), "try{resetGridSelection" + ClientID + "();}catch(ex){}", true);

        }

        public int VirtualItemCount
        {
            get { return grid.VirtualItemCount; }
            set { grid.VirtualItemCount = value; }
        }

        public Object DataSource
        {
            get { return grid.DataSource; }
            set { grid.DataSource = value; }
        }

        protected virtual void grid_OnSortCommand(Object sender, DataGridSortCommandEventArgs e)
        {
            SelectedIndex = -1;

            if (e.SortExpression != SortExpression)
            {
                SortDirection = SORT_ASC;
                SortExpression = e.SortExpression;
            }
            else if (SortDirection == SORT_ASC)
                SortDirection = SORT_DESC;
            else if (SortDirection == SORT_DESC)
            {
                SortDirection = "";
                SortExpression = "";
            }
            hidSelectedID.Value = "";
            Refresh();
        }

        protected virtual void grid_OnPageIndexChanged(Object sender, DataGridPageChangedEventArgs e)
        {
            SelectedIndex = -1;
            CurrentPageIndex = e.NewPageIndex;
            hidSelectedID.Value = "";
            Refresh();
        }

        public String SelectedValue
        {
            get { return hidSelectedID.Value; }
            set { hidSelectedID.Value = value;}
        }

        protected virtual void grid_OnItemCreated(Object sender, DataGridItemEventArgs e)
        {
            DataGrid grid = sender as DataGrid;
            if (e.Item.ItemType == ListItemType.Header)
            {
                e.Item.Attributes.Add("class", "CustomGridHeader");
                if (grid.AutoGenerateColumns == false)
                {
                    for (int i = 0; i < e.Item.Cells.Count; i++)
                    {
                        DataGridColumn col = (DataGridColumn)grid.Columns[i];
                        if (col.SortExpression == SortExpression && SortExpression != String.Empty)
                        {
                            Image img = new Image();
                            img.CssClass = "SortImage";
                            if (SortDirection == SORT_ASC)
                            {
                                img.ImageUrl = "images/icon_arrow_up.gif";
                                e.Item.Cells[i].Controls.Add(img);
                            }
                            else if (SortDirection == SORT_DESC)
                            {
                                img.ImageUrl = "images/icon_arrow_down.gif";
                                e.Item.Cells[i].Controls.Add(img);
                            }
                        }
                    }
                    Control ctrl = e.Item.FindControl("cbSelectAll");
                    if (ctrl != null)
                        ((CheckBox)ctrl).Attributes.Add("onclick", String.Format("selectAll{0}(this)", ClientID));
                }
                else
                {
                    for (int i = 0; i < e.Item.Cells.Count; i++)
                    {
                        e.Item.Cells[i].Style.Add("text-align", "left");
                        e.Item.Cells[i].Text = Utilities.CamelStringSplitter(e.Item.Cells[i].Text);
                    }
                }
            }
            else if (e.Item.ItemType == ListItemType.Item)
            {
                if (grid.DataKeys.Count > 0)
                    e.Item.Attributes.Add("id", string.Format("{0}_row_{1}", ClientID, grid.DataKeys[e.Item.ItemIndex]));

                if(grid.DataKeys.Count > 0 && grid.DataKeys[e.Item.ItemIndex].ToString() == hidSelectedID.Value)
                    e.Item.Attributes.Add("class", "CustomGridSelectedItem");
                else
                    e.Item.Attributes.Add("class", "CustomGridItem");
                e.Item.Attributes.Add("orgclass", "CustomGridItem");
                
                if(grid.DataKeys.Count > 0)
                    e.Item.Attributes.Add("ItemID", grid.DataKeys[e.Item.ItemIndex].ToString());
                if (AllowSelecting)
                {
                    if (OnDblClick.Trim() != "")
                        e.Item.Attributes.Add("ondblclick", OnDblClick);
                    if(OnClientClick.Trim() != "")
                        e.Item.Attributes.Add("onclick", String.Format("onItemClick{0}(this);{1}", ClientID, OnClientClick));
                    else
                        e.Item.Attributes.Add("onclick", String.Format("onItemClick{0}(this)", ClientID));
                }
                Control ctrl = e.Item.FindControl("cbSelect");
                if (grid.DataKeys.Count > 0 && grid.DataKeys[e.Item.ItemIndex].ToString() == hidSelectedID.Value)
                    ((CheckBox)ctrl).Checked = true;
                else
                    ((CheckBox)ctrl).Checked = false;
                if (ctrl != null)
                    ((CheckBox)ctrl).Attributes.Add("onclick", String.Format("clickOnCheckBox{0}(this);", ClientID));
            }
            else if (e.Item.ItemType == ListItemType.AlternatingItem)
            {
                if(grid.DataKeys.Count > 0)
                    e.Item.Attributes.Add("id", string.Format("{0}_row_{1}", ClientID, grid.DataKeys[e.Item.ItemIndex]));
                if (grid.DataKeys.Count > 0 && grid.DataKeys[e.Item.ItemIndex].ToString() == hidSelectedID.Value)
                    e.Item.Attributes.Add("class", "CustomGridSelectedItem");
                else
                    e.Item.Attributes.Add("class", "CustomGridAlternatingItem");
                e.Item.Attributes.Add("orgclass", "CustomGridAlternatingItem");
                if (grid.DataKeys.Count > 0)
                    e.Item.Attributes.Add("ItemID", grid.DataKeys[e.Item.ItemIndex].ToString());
                if (AllowSelecting)
                {
                    if (OnDblClick.Trim() != "")
                        e.Item.Attributes.Add("ondblclick", OnDblClick);
                    if (OnClientClick.Trim() != "")
                        e.Item.Attributes.Add("onclick", String.Format("onItemClick{0}(this);{1}", ClientID, OnClientClick));
                    else
                        e.Item.Attributes.Add("onclick", String.Format("onItemClick{0}(this)", ClientID));
                }
                Control ctrl = e.Item.FindControl("cbSelect");
                if (grid.DataKeys.Count > 0 && grid.DataKeys[e.Item.ItemIndex].ToString() == hidSelectedID.Value)
                    ((CheckBox)ctrl).Checked = true;
                else
                    ((CheckBox)ctrl).Checked = false;
                if (ctrl != null)
                    ((CheckBox)ctrl).Attributes.Add("onclick", String.Format("clickOnCheckBox{0}(this);", ClientID));
            }
            else if (e.Item.ItemType == ListItemType.Pager)
            {
                e.Item.Attributes.Add("class", "CustomGridPager");
            }
            else if (e.Item.ItemType == ListItemType.Footer)
            {
                e.Item.Attributes.Add("class", "CustomGridFooter");
            }
            //else if (e.Item.ItemType == ListItemType.SelectedItem)
            //{
            //    e.Item.Attributes.Add("class", "CustomGridSelectedItem");
            //    Control ctrl = e.Item.FindControl("cbSelect");
            //    if (ctrl != null)
            //        ((CheckBox)ctrl).Checked = true;
            //}
        }

        protected virtual void grid_OnItemDataBound(Object sender, DataGridItemEventArgs e)
        {
            //e.Item.ItemType == ListItemType.
        }

        public void Commit()
        {
            SourceObject.Save();
        }
    }
}